<template>
  <el-dialog :visible.sync="visibleItem" :title="name" append-to-body  width="70%">
    <div style="display: flex;">
    <el-menu v-if="visibleItem"
                    :default-active="defaultActive"
                    class=""
                    @select="handleSelect"
                    style="flex: 1; margin-right: 10px;background: #e6f7ff;"
                    active-text-color="#409eff">
                    
                    <el-menu-item index="review">
                        <i class="el-icon-s-check"></i>
                        <span>审核状态</span>
                    </el-menu-item>
                    <el-menu-item index="processing">
                        <i class="el-icon-s-order"></i>
                        <span>处理状态</span>
                    </el-menu-item>
                </el-menu>
         <div class="policy-knowledge-base" style="flex: 7" v-if="activeTab === 'review'">
            <!-- 标题及刷新 -->
            <div class="header">
              <div class="status-select">
                <el-select v-model="selectedAuditStatus" placeholder="选择模型" size="small" @change="selVal">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="待审核" value="0"></el-option>
                  <el-option label="被驳回" value="2"></el-option>
                </el-select>
                <span class="refresh" @click="refreshData">刷新</span>
              </div>
            </div>
            <!-- 状态选择 -->

            <!-- 内容区域 -->
            <el-scrollbar>
            <div v-if="activeTab === 'review'" class="content" style="width: 100%; height: 400px;" v-loading.fullscreen.lock="loading" element-loading-text="审核中..." element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.3)">
              <div class="item" v-for="(item,index) in policies" :key='index'>
                <div class="item-info">
                  <el-tooltip :disabled="!isOverflowed3" class="item-name1" effect="dark" :content="item.name" placement="top"><span class="item-name" :class="`item-name3-${index}`" @mouseenter="checkOverflow3(index)"  ref="textContainer3">{{item.name}}</span></el-tooltip>
                  <!-- <span class="item-name">{{item.name}}</span> -->
                  <!-- <span class="item-status" style="background: #ffaa00;" v-show="item.auditState == 1 && item.status=='pending'" @click="detail(item)">未处理</span>
                  <span class="item-status" style="background: #aaaa00;" v-show="item.auditState == 1 && item.status=='processing'" @click="detail(item)">处理中</span>
                  <span class="item-status" style="background: #ff0000;" v-show="item.auditState == 1 && item.status=='failed'" @click="detail(item)">处理失败</span> -->
                  <span class="item-status available" style="background: #ebb563;" v-show="item.auditState == 0" @click="detail(item)">待审核</span>
                  <span class="item-status available" style="background: #ff0000;" v-show="item.auditState == 2" @click="detail(item)">被驳回</span>
                  <!-- <span class="item-status available" v-show="item.auditState == 1 && item.status=='processed'" @click="detail(item)">已可用</span> -->
                </div>
                <div class="item-extra">
                  <div class="file-info">{{item.type}} / {{item.content_length / 1024 > 1024 ? (item.content_length / 1024 / 1024).toFixed(2) + ' MB' : (item.content_length / 1024).toFixed(2) + ' KB'}} </div>
                  <div>
                    <span style="margin-right: 5px;">{{ item.created_at }}</span>
                    <span v-if="item.auditState == 0 && kdAuditRole" class="operate audit" @click="audit(item)">审核</span>
                    <span class="operate" @click="download(item)">查看</span>
                    <span class="operate delete" @click="deleteItem(item)">删除</span>
                  </div>
                </div>
              </div>
              <div class="add-btn">
                <!-- <span>+</span> -->
              <!--  <el-upload action="#" ref="uploadRef" list-type="picture-card"
                	:auto-upload="false" :show-file-list="false"
                	:on-change="(file, fileList) => { handlePictureCardPreview(file, fileList) }"
                	:on-remove="handleRemove">
                	<i class="el-icon-plus" v-show="!dialogImageUrl"></i>
                	<img width="100%" :src="dialogImageUrl" alt="">
                </el-upload> -->
                <el-upload :action="$baseUrl + '/common/upload'"  :headers="headers"  ref="uploadRef" list-type="picture-card"
                 :on-success="handleSuccess"
                	:auto-upload="true" :show-file-list="false">
                	<i class="el-icon-plus" v-show="!dialogImageUrl"></i>
                	<img width="100%" :src="dialogImageUrl" alt="">
                </el-upload>
              </div>
            </div>
               </el-scrollbar>
            <!-- 确认按钮 -->
            <div class="confirm-btn">
              <button @click="visibleItem=false">确认</button>
            </div>
          </div>

          <div class="policy-knowledge-base" style="flex: 7" v-if="activeTab === 'processing'">
            <!-- 标题及刷新 -->
            <div class="header">
              <div class="status-select">
                <el-select v-model="selectedStatus" placeholder="选择状态" size="small" @change="selVal2">
                  <el-option label="全部" value=""></el-option>
                  <el-option label="未处理" value="pending"></el-option>
                  <el-option label="处理中" value="processing"></el-option>
                  <el-option label="处理失败" value="failed"></el-option>
                  <el-option label="已可用" value="processed"></el-option>
                </el-select>
                <span class="refresh" @click="refreshData">刷新</span>
              </div>
            </div>
            <!-- 状态选择 -->

            <!-- 内容区域 -->
            <el-scrollbar>
            <div v-if="activeTab === 'processing'" class="content" style="width: 100%; height: 400px;">
              <div class="item" v-for="(item,index) in policies2" :key='index'>
                <div class="item-info">
                  <el-tooltip :disabled="!isOverflowed3" class="item-name1" effect="dark" :content="item.name" placement="top"><span class="item-name" :class="`item-name3-${index}`" @mouseenter="checkOverflow3(index)"  ref="textContainer3">{{item.name}}</span></el-tooltip>
                  <!-- <span class="item-name">{{item.name}}</span> -->
                  <!-- <span class="item-status available" style="background: #ffaa00;" v-show="item.status=='pending'">未处理</span>
                  <span class="item-status available" style="background: #aaaa00;" v-show="item.status=='processing'">处理中</span>
                  <span class="item-status available" style="background: #ff0000;" v-show="item.status=='failed'">处理失败</span> -->
                  <span class="item-status available" style="background: #ffaa00;" v-show="item.auditState == 1 && item.status=='pending'" @click="detail(item)">未处理</span>
                  <span class="item-status available" style="background: #aaaa00;" v-show="item.auditState == 1 && item.status=='processing'" @click="detail(item)">处理中</span>
                  <span class="item-status available" style="background: #ff0000;" v-show="item.auditState == 1 && item.status=='failed'" @click="detail(item)">处理失败</span>
                  <!-- <span class="item-status available" style="background: #67c23a;" v-show="item.status=='processed'" @click="detail(item)">已可用</span> -->
                   <span class="item-status available" style="background: #67c23a;" v-show="item.auditState == 1 && item.status=='processed'" @click="detail(item)">已可用</span>
                </div>
                <div class="item-extra">
                  <div class="file-info">{{item.type}} / {{item.content_length / 1024 > 1024 ? (item.content_length / 1024 / 1024).toFixed(2) + ' MB' : (item.content_length / 1024).toFixed(2) + ' KB'}}</div>
                  <div>
                    <span style="margin-right: 5px;">{{ item.created_at }}</span>
                    <!-- <span v-if="item.auditState != 1" class="operate audit" @click="audit">审核</span> -->
                    <span class="operate" @click="download(item)">查看</span>
                    <span class="operate delete" @click="deleteItem(item)">删除</span>
                  </div>
                </div>
              </div>
              
            </div>
               </el-scrollbar>
            <!-- 确认按钮 -->
            <div class="confirm-btn">
              <button @click="visibleItem=false">确认</button>
            </div>
          </div>
          <!-- 关联知识库 -->
          <PreviewArea ref="Preview"/>

          <!-- 审核 -->
           <AuditDialog ref="audit" @changeAuditState="onChangeAuditState"></AuditDialog>

           <!-- 详情 -->
            <DetailDialog ref="detail"></DetailDialog>
       </div>    
  </el-dialog>
</template>

<script>
    import moment from 'moment';
import PreviewArea from './PreviewArea.vue'
import AuditDialog from './AuditDialog.vue';

import DetailDialog from './DetailDialog.vue';
export default {
  components: {
    PreviewArea,
    AuditDialog,
    DetailDialog
  },
  data() {
    return {
      headers:{
        Authorization:sessionStorage.getItem('token')
      },
      visibleItem:false,
      dialogImageUrl: '',
      policies: [],
      policies2: [],
      selectedStatus: '',
      selectedAuditStatus: '',
      name:'',
      ragsId: '',
      raw:'',
      status:'',
      auditState: '',
      isOverflowed3: false,
      visibleAudit: false,
      activeTab: 'review',
      loading: false,
      defaultActive: "review",
      kdAuditRole: false
    };
  },
  mounted() {
    // this.$nextTick(() => {
    //   this.checkOverflow3(0)
    // })
    this.$httpApi.getLoginUserInfo().then((res) => {
      if (res.success) {
        this.kdAuditRole = res.data.kdAuditRole
      }
    });
    
    
  },
  methods: {
    audit(item) {
      this.$refs.audit.open(item)
    },
  checkOverflow3(index) {
    const el = document.querySelector(`.item-name3-${index}`)
    if(!el) return
    console.log(el, 'el')
      // 比较实际内容宽度与可视宽度
      this.isOverflowed3 = el.scrollWidth > el.clientWidth
      console.log(this.isOverflowed3, 'isOverflowed3')
  },
    selVal(el){
      this.auditState=el
      console.log(el)
      this.getList()
    },
    selVal2(el){
      this.status=el
      console.log(el)
      this.getList()
    },
    open(row){
      console.log(row, 'row')
       this.visibleItem = true
        this.name=row.ragsName
        this.ragsId = row.ragsId
        // this.selectedStatus = ''
        // this.selectedAuditStatus = ''
        //               this.auditState = ''
        //               this.status = ''
                      //  this.activeTab = 'review'
                      // this.handleSelect('review')
                      this.handleSelect(this.activeTab)
                      this.defaultActive = this.activeTab

        // this.getList()
    },
    deleteItem(row){
      console.log(row, '删除知识库文档')
      this.$confirm('你确定要删除这条数据吗？', '警告', {
        type: 'warning',
      }).then(() => {
        // const params = {
        //   name:this.name,
        //   docName:row.file_path
        // }
        const params = row.id
        this.$httpApi.deleteDocuments(params).then((res) => {
          // if(res.success) {
          //     let data=JSON.parse(res.data)
          //     if(data.code==200){
          //       this.$message.success('操作成功');
          //       this.getList()
          //     }else{
          //       this.$message.error('删除失败！');
          //     }
          // }else{
          //   this.$message.error(res.msg);
          // }
          if(res.code == 200) {
            this.$message.success('操作成功');
            this.getList()
          } else {
            this.$message.error(res.msg);
          }
        })
      }, () => {
      })
    },
    isEmpty(obj) {
      return Object.keys(obj).length === 0;
    },
    mergeArrays(...arrays) {
        return [].concat(...arrays.filter(array => array !== undefined));
    },
    getList(){
    //  let params = {
    //    name: this.name,
    //    status:this.status
    //  }
    let params = {
        orderByColumn: '',
        orderByAsc: true,
        pageIndex: 1,
        pageSize: 1000,
        keyword: '',
        ragsId: this.ragsId,
        status: this.status || '',
        auditState: this.auditState || '',
      }
     let arrStr=[]
     this.$httpApi.documents(params).then((res) => {
      console.log(res, 'ressss')
       if (res.success) {
        //  // this.knowledgeBases = res.data
        //  let jsonStr1=JSON.parse(res.data).statuses
        //  // let jsonStr1=JSON.parse(res.data).statuses.pending
        //  // let jsonStr2=JSON.parse(res.data).statuses.processing
        //  // let jsonStr3=JSON.parse(res.data).statuses.failed
        //  // let jsonStr4=JSON.parse(res.data).statuses.processed
        //  if(this.isEmpty(jsonStr1)){
        //     this.policies=[]
        //     return
        //  }else{
        //     arrStr = this.mergeArrays(jsonStr1.pending, jsonStr1.processing, jsonStr1.failed, jsonStr1.processed);
        //  }
        // // console.log('~~~~~~~~~',arrStr)
        //  const arr = eval(arrStr);
        //  const arr1 = arrStr;
        //  console.log(arr1, 'arr1')
          const arr1 = res.data.list;
          console.log(arr1, 'arr1')
         let NewArr=[]
         for(let i=0;i<arr1.length;i++){
           let obj={
            //  file_path:arr1[i].file_path,
            //  name:arr1[i].file_path.split('.')[0],
            //  type:arr1[i].file_path.split('.')[1],
            //  status:arr1[i].status,
            //  content_length:arr1[i].content_length,
            //  created_at: moment(arr1[i].created_at).format('yyyy-MM-DD HH:mm')

            // filename:arr1[i].documentsName,
            //  name:arr1[i].documentsName.split('.')[0],
            //  type:arr1[i].documentsName.split('.')[1],
            //  status:arr1[i].status,
            //  content_length:arr1[i].size,
            //  created_at: moment(arr1[i].createTime).format('yyyy-MM-DD HH:mm')
            filename:arr1[i].documentsName,
             name:arr1[i].documentsName.split('.')[0],
             type:arr1[i].documentsExtension,
             status:arr1[i].status,
             content_length:arr1[i].documentsSize,
             created_at: moment(arr1[i].createTime).format('yyyy-MM-DD HH:mm'),
             auditState: arr1[i].auditState,
             id: arr1[i].id,
           }
           NewArr.push(obj)
         }
        this.policies=NewArr.filter(item => item.auditState != 1)
        this.policies2=NewArr.filter(item => item.auditState == 1)
        console.log(this.policies, 'this.policies')
        console.log(this.policies2, 'this.policies2')
       }
     })
    },
    handleRemove(file, fileList) {
    	console.log(file, fileList);
    },
    handleSuccess(res){
      console.log('上传成功',res)
      this.UploadDoc(res.data)
    },
    handlePictureCardPreview(file) {
    	this.raw = file.raw
    	// this.dialogImageUrl = file.url;
      console.log('提交',file.raw)
      let parms = new FormData();
      // parms.append('file',file.raw)
      parms.append('type','any')
      this.$httpApi.uploadFileAny(parms).then((res) => {
        if (res.success) {
         //  let jsonStr=JSON.parse(res.data).statuses.processed
         //  const arr1 = eval(jsonStr);
         // this.policies=arr1
           this.$message.success('数据提交成功');
        }
        else{
          this.$message.error(res.msg);
        }
      })
    	console.log(file)
    },
    refreshData() {
      this.getList()
      this.$message.success('已刷新');
    },
    // 上传
    UploadDoc(row){
      // let params = {
      //   name: this.name,
      //   filePath:row.filename
      // }
      console.log(row, 'row----')
      let params = {
        id: '',
        // documentsName: row.filename.split('.')[0],
        documentsName: row.filename,
        // size: row.size,
        // ragsId: this.ragsId,
        auditState: '',
        auditDesc: '',
        auditTime: '',
        status: '',
        userId: '',
        ragsId: this.ragsId,
        fileId: row.id
      }
      this.$httpApi.documentsUpload(params).then((res) => {
        console.log(res, 'res111')
        if (res.success) {
         //  let jsonStr=JSON.parse(res.data).statuses.processed
         //  const arr1 = eval(jsonStr);
         // this.policies=arr1
         this.$message.success('提交成功');
         this.getList()
        }
        else{
          this.$message.error(res.msg);
        }
      })
    },
    viewPolicy(policy) {
      console.log('查看政策:', policy);
    },
    deletePolicy(policy) {
      // 删除政策的逻辑
      const index = this.policies.indexOf(policy);
      if (index !== -1) {
        this.policies.splice(index, 1);
      }
    },
    download(item) {
      this.$refs.Preview.open(item)
      // window.open('/upload/' + item.file_path)
    },
    handleSelect(key) {
                    this.activeTab = key;
                    if(key === 'review') {
                      this.selectedStatus = ''
                      this.auditState = ''
                      this.status = ''
                    } else if(key === 'processing') {
                      this.selectedAuditStatus = ''
                      this.auditState = ''
                      this.status = ''
                    }
                    this.getList()
                },
                onChangeAuditState(obj) {
                  console.log(obj, 'obj')
                  const params = {
                    id: obj.id,
                    auditState: obj.flag ? 1 : 2, // 1表示通过，2表示驳回
                    auditDesc: obj.auditDesc || '',
                    // auditTime: obj.flag ? moment().format('YYYY-MM-DD HH:mm:ss') : '',
                    // auditTime: '',
                    documentsName: obj.name || '',
                    ragsId: this.ragsId,
                    // status: obj.flag ? 'processed' : 'failed',
                    status: '',
                    userId: '',
                  }
                  if(obj.flag) {
                    this.loading = true
                    // 审核通过
                    this.$httpApi.passDocuments(params).then((res) => {
                      console.log(res, '审核')
                      if(res.success) {
                        this.$message.success('审核通过');
                        this.getList()
                      } else {
                        this.$message.error('审核未通过');
                      }
                      this.loading = false
                    })
                  } else {
                    this.$httpApi.unPassDocuments(params).then((res) => {
                      console.log(res, '驳回')
                      if(res.success) {
                        this.$message.success('审核未通过，已驳回');
                        this.getList()
                      } else {
                        this.$message.error('驳回失败');
                      }
                    })
                    // this.$message.error('审核未通过，已驳回');
                  }
                },
                detail(item) {
                  this.$refs.detail.open(item)
                }

  },
};
</script>

<style scoped>
.policy-knowledge-base {
  width: 100%; /* 可根据实际调整宽度 */
  margin: 0 auto;
  font-family: sans-serif;
}
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}
.title {
  font-size: 18px;
  font-weight: bold;
}
.refresh {
  color: #409eff;
  cursor: pointer;
  margin-left: 15px;
}
.status-select select {
  padding: 4px;
  border: 1px solid #dcdcdc;
  border-radius: 4px;
  margin-bottom: 15px;
}
.content {
 /* display: flex;
  align-items: flex-start;
  margin-bottom: 20px; */
  max-height: 390px;
  overflow: scroll;
   display: grid;
    grid-template-columns: repeat(3, 1fr); /* 创建三列 */
    gap: 10px; /* 设置间距 */
    grid-auto-rows: 80px; /* 强制每行高度为 80px */
}
.item {
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
  border: 1px solid #e6e6e6;
  border-radius: 4px;
  padding: 10px;
  margin-right: 15px;
  height: 80px;
}
.item-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}
.item-name {
  font-weight: bold;
  max-width: 200px;
  display: inline-block;
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏溢出的内容 */
    text-overflow: ellipsis; /* 显示省略符号来代表被修剪的文本 */
}
.item-status {
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  color: #fff;
}
.available {
  /* background: #67c23a; */
  cursor: pointer;
}
.item-extra {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.file-info {
  font-size: 12px;
  color: #999;
}
.operate {
  font-size: 12px;
  color: #409eff;
  cursor: pointer;
  margin-left: 8px;
}
.delete {
  color: #f56c6c;
}
.audit {
  color: #ebb563;
}
.add-btn {
  width: 65px;
  height: 65px;
  border: 1px dashed #dcdcdc;
  border-radius: 4px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 24px;
  color: #999;
  cursor: pointer;
}
.confirm-btn {
  text-align: right;
}
.confirm-btn button {
  padding: 6px 16px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
>>>.el-upload--picture-card{
  width: 100%;
      height: 100%;
      line-height:1.6;
      border:0;
}
</style>


